
#import sectionizer
import os
from whiff import parseTemplate
from whiff import urlcomponent
from whiff.middleware import misc
from whiff import whiffenv
from whiff import resolver
from whiff import gateway

class getSectionPosition(misc.utility):
    def __init__(self, path, page):
        self.path = path
        self.page = page
    def __call__(self, env, start_response):
        navigationData = gateway.getResource(env, ["navigationData"])
        path = self.param_value(self.path, env)
        (directory, filename) = os.path.split(path)
        entrypoint = env.get(whiffenv.ENTRY_POINT)
        # if entry point is available, override the filename
        if entrypoint:
            (dummy, filename) = os.path.split(entrypoint)
            if filename=="colorize":
                # if colorize then use the "page" cgi argument instead
                env = resolver.process_cgi(env, parse_cgi=True)
                filename = whiffenv.cgiGet(env, "page", filename)
            filename += ".whiff"
        #sect = sectionizer.Sectionizer(directory, "W")
        #env["sectionizer"] = sect
        env["filename"] = filename
        id = env["documentName"] = ".".join(filename.split(".")[:-1])
        navDict = navigationData[id]
        #env["directory"] = directory
        env = env.copy()
        #env["ancestors"] = [self.templateInfo(directory,c) for c in info.ancestors]
        children = navDict["children"]
        if children:
            env["children"] = [navigationData[child] for child in children]
        env["self"] = navDict
        previous = navDict["previous"]
        if previous:
            env["previous"] = navigationData[previous]
        next = navDict["next"]
        if next:
            env["next"] = navigationData[next]
        up = navDict.get("parent")
        if up:
            env["up"] = navigationData[up]
        env["nextChild"] = os.path.join(directory, "FILE_NAME_HERE")
        return self.deliver_page(self.page, env, start_response)
    def templateInfo(self, directory, filename):
        return templateInfo(directory, filename)

def templateInfo(directory, filename):
    "extract url, title and summary from template"
    D = {}
    # get url by stripping of ".whiff"
    url = filename[:-6]
    # parse the template
    filepath = os.path.join(directory, filename)
    text = file(filepath).read()
    (test, page, cursor) = parseTemplate.parse_page(text, file_path=filepath)
    # find the url component
    urlcomp = None
    for component in page.get_components():
        if isinstance(component, urlcomponent.UrlComponent):
            urlcomp = component
    if urlcomp is not None:
        # extract the TEXT of the title and summary
        arguments = urlcomp.get_arguments_dictionary()
    else:
        arguments = {}
    if arguments.has_key("title"):
        title = arguments["title"].text
    else:
        title = "untitled: "+filepath
    if arguments.has_key("summary"):
        summary = arguments["summary"].text
    else:
        summary = "no summary: "+filepath
    if arguments.has_key("body"):
        body = arguments["body"].text
    else:
        body = "no body: "+filepath
    D["url"] = url
    D["title"] = title
    D["summary"] = summary
    D["body"] = body
    return D

__middleware__ = getSectionPosition

def test():
    env = {}
    def start_response(*args):
        print "test start response:", args
    def testapp(env, start_response):
        start_response('200 OK', [('Content-Type', 'text/plain')])
        yield "environment dump\n"
        for x in env.items():
            yield x
            yield "\n"
        yield "length="+str( len(env))
    app = getSectionPosition("./W1200_1000.DirectoryConfig.whiff", testapp)
    result = app(env, start_response)
    print "test result="
    print "".join(list(result))

if __name__=="__main__":
    test()
